package lt.pop3client.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import lt.pop3client.exception.ClientException;

import org.apache.log4j.Logger;


public class Client {
	private static Logger log = Logger.getLogger(Client.class);
	
	private String host;
	private int port;
	
	private Socket server;
	private BufferedReader serverResponseStream;
	private PrintWriter serverRequestStream;
	
	public Client(String host, int port){
		this.host = host;
		this.port = port;
	}
	
	public void connect() throws ClientException{
		try {
			log.debug("Getting connections...");
			server = new Socket(host,port);
			log.debug("connected.");
			
			log.debug("Getting streams...");
			serverRequestStream = new PrintWriter(server.getOutputStream());
			serverResponseStream = new BufferedReader(new InputStreamReader(server.getInputStream()));
			log.debug(readResponseLine());
			log.debug("Streams got.");
		} catch (UnknownHostException uhe){
			log.debug("Nezinomas hostas.");
			throw new ClientException(1,"Nezinomas nurodytas hostas");
		} catch (IOException e) {
			log.debug("Nezinoma IO klaida");
			throw new ClientException(-1,"Nenumatyt klaida");
		}
	}
	public String sendCommand(String command) throws ClientException{
		try {
			serverRequestStream.write(command + "\r\n");
			serverRequestStream.flush();
			
			return readResponseLine();
		} catch (IOException ioe){
			log.debug("Error sending command." + ioe.getMessage());
			throw new ClientException(3,"Error sending command");
		}
	}
	
	public String readResponseLine() throws IOException,ClientException{
		String response = serverResponseStream.readLine();
		log.debug(response);
		if (response.startsWith("-ERR")){
			throw new ClientException(2,"Server has returned an error: " + response.replaceFirst("-ERR ", ""));
		}
		return response;
	}
	
	public void disconnect(){
		serverRequestStream.close();
		serverRequestStream.close();
		try {
			server.close();
		} catch (IOException ioe){
			log.error("Error when disconnecting.",ioe);
		}
	}
}
